#!/usr/bin/env bash
${v:+set -x}

usage() {
  echo "labeling <namespace> <registry> <harbor-base64(username:password)> <new-tag>"
}

if [ $# -ne 4 ]
then
  usage
  exit 1
fi

namespace=$1
candidate=$2
authorize=$3
thenewtag=$4

while read -r c
do
  # docker-pullable://reg.devops.x-chain.tech/mw/aedes@sha256:b3e11ea0660cd980fc4a238bfc51e2e958f4ae1580e2200c8440536e84fb4200
  id=$(kubectl describe pod "$c" -n "${namespace}"|grep -Eo "Image ID.*"|awk '{print $3}')
  # reg.devops.x-chain.tech/mw/aedes@sha256:b3e11ea0660cd980fc4a238bfc51e2e958f4ae1580e2200c8440536e84fb4200
  raw=${id:18}
  # sha256:b3e11ea0660cd980fc4a238bfc51e2e958f4ae1580e2200c8440536e84fb4200
  reference=${raw##*@}
  # reg.devops.x-chain.tech
  registry=${raw%%/*}
  # mw/aedes@sha256:b3e11ea0660cd980fc4a238bfc51e2e958f4ae1580e2200c8440536e84fb4200
  raw=${raw#*/}
  # mw
  project=${raw%%/*}
  # aedes@sha256:b3e11ea0660cd980fc4a238bfc51e2e958f4ae1580e2200c8440536e84fb4200
  raw=${raw#*/}
  # aedes
  repository=${raw%%@*}

  if [ "${registry}" != "${candidate}" ]
  then
    continue
  fi

  echo -en "${project}/${repository}@${reference} ... tagging="
  curl -X POST -H 'content-type:application/json' -vskS \
    -H "Authorization: Basic ${authorize}" \
    "https://${registry}/api/v2.0/projects/${project}/repositories/${repository}/artifacts/${reference}/tags" \
    -d "{\"name\":\"${thenewtag}\"}" 2>&1|grep -Eo "^< HTTP/[0-9]+ [0-9]+"|awk '{print $3}'
done <<< "$(kubectl get pods -n "${namespace}" -o json|jq .items[].metadata.name|tr -d '"')"
